import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:mall/components/image_network.dart';
import 'package:mall/constants.dart';
import 'package:mall/core/models/jump_type.dart';
import 'package:mall/core/models/store_index.dart';
import 'package:mall/core/models/user_total.dart';
import 'package:mall/core/providers/app_model.dart';
import 'package:mall/core/services/api.dart';
import 'package:mall/screens/home/home_store_screen.dart';
import 'package:mall/screens/mine/login_page.dart';
import 'package:mall/screens/mine/store_apply_page.dart';
import 'package:mall/screens/mine/webview_page.dart';
import 'package:mall/screens/product/product_area_screen.dart';
import 'package:mall/screens/store/store_screen.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:provider/provider.dart';

import '../home_category_screen.dart';

/// 导航
class HomeNavigator extends StatelessWidget {
  const HomeNavigator({
    Key key,
    @required this.navigator,
  }) : super(key: key);
  final List<Link> navigator;

  @override
  Widget build(BuildContext context) {
    return Wrap(
      spacing: 12.5.w,
      runSpacing: 8.w,
      children: List.generate(navigator.length, (index) => _buildItem(context, index)),
    );
  }

  Widget _buildItem(BuildContext context, int index) {
    final link = navigator[index];
    return GestureDetector(
      onTap: () => _onTap(context, link),
      child: SizedBox(
        width: 60.w,
        child: Column(
          children: [
            ImageNetwork(
              url: "${link.image}",
              width: 30.w,
              height: 30.w,
            ),
            SizedBox(
              height: 1.w,
            ),
            Text(
              "${link.title}",
              style: TextStyle(fontSize: 13.sp),
            ),
          ],
        ),
      ),
    );
  }

  /// 点击导航
  void _onTap(BuildContext context, Link link) {
    final uri = Uri.tryParse("$api_base_url?${link.link}");
    debugPrint("${uri?.queryParameters}");
    final storeId = int.tryParse("${uri?.queryParameters["storeId"]}");
    final catalogId = int.tryParse("${uri?.queryParameters["catalogId"]}");
    final storeAreaId = int.tryParse("${uri?.queryParameters["storeAreaId"]}");
    switch (link.jumpType) {
      case JumpType.JUMP_IN_STORE:
        Navigator.of(context).pushNamed(StoreScreen.routeName, arguments: storeId);
        break;
      case JumpType.JUMP_IN_STORE_AREA:
        Navigator.of(context).pushNamed(
          ProductAreaScreen.routeName,
          arguments: ProductAreaScreenArgs(
            storeId: storeId,
            categoryId: catalogId,
            areaId: storeAreaId,
            name: "${link.title}",
          ),
        );
        break;
      case JumpType.JUMP_IN_PRODUCT_CATALOG:
        Navigator.of(context).pushNamed(
          HomeCategoryScreen.routeName,
          arguments: HomeCategoryScreenArgs(false),
        );
        break;
      case JumpType.JUMP_IN_MY_STORE:
        _jumpInMyStore(context, storeId);
        break;
      case JumpType.JUMP_IN_STORE_SEARCH:
        Navigator.of(context).pushNamed(HomeStoreScreen.routeName);
        break;
      default:
    }
  }

  void _jumpInMyStore(BuildContext context, int storeId) async {
    // 在没有登录之前，首页上的“我的店铺”点击时应该跳转到登录页面。
    // 在已登录的情况下，如果用户未开通店铺，此时点击，则直接进入店铺申领流程。
    final appModel = context.read<AppModel>();

    // 没有登录
    if (appModel.accessToken == null) {
      Navigator.of(context).pushNamed(LoginPage.routeName);
      return;
    }

    // 已经申请店铺
    if (storeId > 0) {
      Navigator.of(context).pushNamed(StoreScreen.routeName, arguments: storeId);
      return;
    }

    // 获取用户信息userTotal
    final userTotal = await _fetchUserTotal(context);
    if (userTotal == null) {
      return;
    }

    // 先显示协议
    final url = userTotal.storeProtocolUrl;
    if (url != null && url.isNotEmpty) {
      final result = await Navigator.of(context).pushNamed(
        WebViewPage.routeName,
        arguments: WebViewPageArgs(
          '店铺申领协议',
          '请仔细阅读以下条款：',
          '$url',
          query: true,
        ),
      );
      if (result == null || result == false) {
        return;
      }
    }

    // 店铺申领
    Navigator.of(context).pushNamed(StoreApplyPage.routeName, arguments: userTotal);
  }

  /// 获取用户信息userTotal
  Future<UserTotal> _fetchUserTotal(BuildContext context) async {
    final api = context.read<Api>();
    EasyLoading.show();
    try {
      var userTotal = await api.userTotal(null);
      EasyLoading.dismiss();
      return userTotal;
    } on DioError catch (e) {
      EasyLoading.showToast("${e.message}");
    } catch (e) {
      EasyLoading.showToast("$e");
    }
    return null;
  }
}
